package com.kk.utils.encryption.symmetry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;

/**
 * the type of advance
 *
 * <p>
 * .
 *
 * @author MH
 * @date 2022-05-09
 */
public class AESUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger("AESUtils");

    /**
     * DES密钥长度必须是8字节
     */
    private static final String KEY_STR = "mykkbaby";
    private static final SecretKey secretKey;

    static {
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(KEY_STR.getBytes(StandardCharsets.UTF_8));
            keyGenerator.init(128, secureRandom);
            // 生成密钥对象（用于加密、解密）
            secretKey = keyGenerator.generateKey();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * DES加密
     *
     * @param s
     * @return
     */
    public static String encryptString(String s) {
        BASE64Encoder base64Encoder = new BASE64Encoder();

        // 获取加密对象
        try {
            Cipher cipher = Cipher.getInstance("AES");
            // 初始化密码信息
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            // 加密
            byte[] bytes = cipher.doFinal(s.getBytes(StandardCharsets.UTF_8));
            // 使用 Base64 再加一层密
            LOGGER.info("==> 待加密: {}", s);
            String encode = base64Encoder.encode(bytes);
            LOGGER.info("==> AES 加密后: {}", encode);
            return encode;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * DES解密
     *
     * @param encode
     * @return
     */
    public static String decryptString(String encode) {
        BASE64Decoder base64Decoder = new BASE64Decoder();
        try {
            // 获取解密对象
            Cipher cipher = Cipher.getInstance("AES");
            // 初始化解密信息
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            // 解密，先用 Base64 解密
            byte[] bytes = cipher.doFinal(base64Decoder.decodeBuffer(encode));
            LOGGER.info("==> 待解密: {}", encode);
            String decode = new String(bytes);
            LOGGER.info("==> AES 解密后: {}", decode);
            return decode;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public static void main(String[] args) {
        String encryptString = encryptString("你好,小柯");
        String s = decryptString(encryptString);
    }
}
